package com.System.LearnSystemTeacher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.System.LearnSystem.Result;
import com.System.LearnSystem.Token;
import com.System.LearnSystem.sqlConnection;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

class deleted
{
	private String token;
	private String role;
	private String course;
	public deleted()
	{
		
	}
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	
}

@WebServlet("/tea/delCourse")
public class delCourse extends HttpServlet{
	public void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		StringBuilder json = new StringBuilder();//读取json请求
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        String jsonStr = json.toString();     
        ObjectMapper objectMapper = new ObjectMapper();
        deleted del = objectMapper.readValue(jsonStr, deleted.class);
        
        objectMapper.registerModule(new JavaTimeModule());//注册驱动保证序列化
        res.setContentType("application/json;charset=UTF-8");//设置响应格式
        PrintWriter out = res.getWriter();
        
        if(del.getToken()!=null) 
        {
        	if(Token.checkToken(del.getToken())&&"TEACHER".equals(del.getRole()))//验证令牌和身份
        	{
	        	String sql = "delete from t_course where course_name = ?;";
	        	try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) 
	        	{
	        		pstmt.setString(1,del.getCourse());
	        		int Line = pstmt.executeUpdate();
	        		System.out.println("受影响的行数为："+Line);
	        	}catch (SQLException e) {
	      		  System.err.println("SQL 错误码: " + e.getErrorCode());
	      		  System.err.println("SQL 错误消息: " + e.getMessage());
	      		    e.printStackTrace();
				}
	        	Result<deleted> result = Result.success(del);
	        	out.println(objectMapper.writeValueAsString(result));
	      	}
	      	else
	      	{
	      		Result<Object> result = Result.error(401,"非授权访问");
	      		out.println(objectMapper.writeValueAsString(result));
	      	}	
      }
      else
      {
      	Result<Object> result = Result.error(401,"非授权访问");
      	out.println(objectMapper.writeValueAsString(result));
      }
	}
}